// pages/food-management/food-management.js
const app = getApp()

Page({
  data: {
    showAddForm: false,
    foodName: '',
    quantity: '',
    unitIndex: 0,
    units: ['克', '千克', '个', '包', '瓶', '盒'],
    expiryDate: '',
    categoryIndex: 0,
    categories: ['蔬菜', '水果', '肉类', '海鲜', '谷物', '豆制品', '调味品', '其他'],
    
    foodList: [],
    searchKeyword: '',
    currentFilter: 'all',
    categoryFilterIndex: 0,
    categoryOptions: ['全部分类', '蔬菜', '水果', '肉类', '海鲜', '谷物', '豆制品', '调味品', '其他'],
    
    expiringCount: 0,
    categoryCounts: [],
    
    showEditModal: false,
    editingFood: null
  },

  onLoad() {
    this.loadFoodData()
  },

  onShow() {
    this.loadFoodData()
  },

  onPullDownRefresh() {
    this.loadFoodData()
    wx.stopPullDownRefresh()
  },

  loadFoodData() {
    const foodList = wx.getStorageSync('foodList') || []
    this.setData({
      foodList: foodList.map(item => ({
        ...item,
        isExpiring: this.checkIfExpiring(item.expiryDate)
      }))
    })
    this.calculateStats()
    this.filterFoodList()
  },

  calculateStats() {
    const { foodList } = this.data
    
    // 计算即将过期数量
    const expiringCount = foodList.filter(item => item.isExpiring).length
    
    // 计算分类统计
    const categoryCounts = [...new Set(foodList.map(item => item.category))]
    
    this.setData({
      expiringCount,
      categoryCounts
    })
  },

  checkIfExpiring(expiryDate) {
    if (!expiryDate) return false
    
    const today = new Date()
    const expiry = new Date(expiryDate)
    const diffTime = expiry.getTime() - today.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    
    return diffDays <= 3 && diffDays >= 0
  },

  // 显示添加表单
  showAddForm() {
    this.setData({
      showAddForm: true,
      foodName: '',
      quantity: '',
      unitIndex: 0,
      expiryDate: '',
      categoryIndex: 0
    })
  },

  hideAddForm() {
    this.setData({
      showAddForm: false
    })
  },

  // 拍照识别（模拟）
  showCamera() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
      success: (res) => {
        // 模拟识别结果
        app.showLoading('识别中...')
        
        setTimeout(() => {
          const tempFilePaths = res.tempFilePaths
          // 这里应该是调用OCR API识别食材
          // 模拟识别结果
          const recognizedFoods = [
            { name: '西红柿', confidence: 0.95 },
            { name: '鸡蛋', confidence: 0.88 },
            { name: '青菜', confidence: 0.82 }
          ]
          
          wx.hideLoading()
          
          wx.showActionSheet({
            itemList: recognizedFoods.map(food => `${food.name} (${(food.confidence * 100).toFixed(0)}%)`),
            success: (res) => {
              const selectedFood = recognizedFoods[res.tapIndex]
              this.setData({
                showAddForm: true,
                foodName: selectedFood.name,
                quantity: '500',
                unitIndex: 0,
                expiryDate: this.getDefaultExpiryDate(),
                categoryIndex: this.guessCategory(selectedFood.name)
              })
            }
          })
        }, 2000)
      }
    })
  },

  getDefaultExpiryDate() {
    const date = new Date()
    date.setDate(date.getDate() + 7) // 默认7天后过期
    return app.formatDate(date)
  },

  guessCategory(foodName) {
    const categories = this.data.categories
    const name = foodName.toLowerCase()
    
    if (name.includes('菜') || name.includes('蔬')) return categories.indexOf('蔬菜')
    if (name.includes('果')) return categories.indexOf('水果')
    if (name.includes('肉') || name.includes('鸡') || name.includes('鸭') || name.includes('猪') || name.includes('牛')) return categories.indexOf('肉类')
    if (name.includes('鱼') || name.includes('虾') || name.includes('蟹') || name.includes('贝')) return categories.indexOf('海鲜')
    if (name.includes('米') || name.includes('面') || name.includes('麦') || name.includes('谷')) return categories.indexOf('谷物')
    if (name.includes('豆') || name.includes('腐')) return categories.indexOf('豆制品')
    
    return categories.indexOf('其他')
  },

  // 输入事件
  onFoodNameInput(e) {
    this.setData({ foodName: e.detail.value })
  },

  onQuantityInput(e) {
    this.setData({ quantity: e.detail.value })
  },

  onUnitChange(e) {
    this.setData({ unitIndex: e.detail.value })
  },

  onExpiryDateChange(e) {
    this.setData({ expiryDate: e.detail.value })
  },

  onCategoryChange(e) {
    this.setData({ categoryIndex: e.detail.value })
  },

  // 添加食材
  addFood() {
    const { foodName, quantity, unitIndex, units, expiryDate, categoryIndex, categories } = this.data
    
    if (!foodName) {
      app.showError('请输入食材名称')
      return
    }
    
    if (!quantity || quantity <= 0) {
      app.showError('请输入正确的数量')
      return
    }
    
    const newFood = {
      id: Date.now().toString(),
      name: foodName,
      quantity: parseFloat(quantity),
      unit: units[unitIndex],
      unitIndex: unitIndex,
      expiryDate: expiryDate || this.getDefaultExpiryDate(),
      category: categories[categoryIndex],
      categoryIndex: categoryIndex,
      createTime: new Date().toISOString(),
      isExpiring: this.checkIfExpiring(expiryDate)
    }
    
    const foodList = [...this.data.foodList, newFood]
    wx.setStorageSync('foodList', foodList)
    
    this.setData({
      foodList,
      showAddForm: false
    })
    
    this.calculateStats()
    this.filterFoodList()
    app.showSuccess('添加成功')
  },

  // 搜索和筛选
  onSearchInput(e) {
    this.setData({ searchKeyword: e.detail.value })
    this.filterFoodList()
  },

  setFilter(e) {
    const filter = e.currentTarget.dataset.filter
    this.setData({ currentFilter: filter })
    this.filterFoodList()
  },

  onCategoryFilterChange(e) {
    this.setData({ categoryFilterIndex: e.detail.value })
    this.filterFoodList()
  },

  filterFoodList() {
    const { foodList, searchKeyword, currentFilter, categoryFilterIndex, categoryOptions } = this.data
    
    let filtered = foodList
    
    // 搜索过滤
    if (searchKeyword) {
      filtered = filtered.filter(item => 
        item.name.toLowerCase().includes(searchKeyword.toLowerCase())
      )
    }
    
    // 分类过滤
    if (categoryFilterIndex > 0) {
      const selectedCategory = categoryOptions[categoryFilterIndex]
      filtered = filtered.filter(item => item.category === selectedCategory)
    }
    
    // 状态过滤
    if (currentFilter === 'expiring') {
      filtered = filtered.filter(item => item.isExpiring)
    } else if (currentFilter === 'low') {
      filtered = filtered.filter(item => item.quantity < 100) // 假设小于100克为库存不足
    }
    
    this.setData({ filteredFoodList: filtered })
  },

  // 编辑食材
  editFood(e) {
    const id = e.currentTarget.dataset.id
    const food = this.data.foodList.find(item => item.id === id)
    
    if (food) {
      this.setData({
        showEditModal: true,
        editingFood: { ...food }
      })
    }
  },

  hideEditModal() {
    this.setData({
      showEditModal: false,
      editingFood: null
    })
  },

  onEditNameInput(e) {
    this.setData({
      'editingFood.name': e.detail.value
    })
  },

  onEditQuantityInput(e) {
    this.setData({
      'editingFood.quantity': e.detail.value
    })
  },

  onEditUnitChange(e) {
    this.setData({
      'editingFood.unitIndex': e.detail.value,
      'editingFood.unit': this.data.units[e.detail.value]
    })
  },

  onEditExpiryDateChange(e) {
    this.setData({
      'editingFood.expiryDate': e.detail.value,
      'editingFood.isExpiring': this.checkIfExpiring(e.detail.value)
    })
  },

  saveEdit() {
    const { editingFood, foodList } = this.data
    
    if (!editingFood.name) {
      app.showError('请输入食材名称')
      return
    }
    
    if (!editingFood.quantity || editingFood.quantity <= 0) {
      app.showError('请输入正确的数量')
      return
    }
    
    const updatedList = foodList.map(item => 
      item.id === editingFood.id ? { ...editingFood } : item
    )
    
    wx.setStorageSync('foodList', updatedList)
    
    this.setData({
      foodList: updatedList,
      showEditModal: false,
      editingFood: null
    })
    
    this.calculateStats()
    this.filterFoodList()
    app.showSuccess('保存成功')
  },

  // 删除食材
  deleteFood(e) {
    const id = e.currentTarget.dataset.id
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个食材吗？',
      success: (res) => {
        if (res.confirm) {
          const updatedList = this.data.foodList.filter(item => item.id !== id)
          wx.setStorageSync('foodList', updatedList)
          
          this.setData({
            foodList: updatedList
          })
          
          this.calculateStats()
          this.filterFoodList()
          app.showSuccess('删除成功')
        }
      }
    })
  }
})